//
//  DanmakuLabel.m
//  testDanmaku
//
//  Created by zhaoyun on 2017/2/13.
//  Copyright © 2017年 ainemo. All rights reserved.
//

#import "DanmakuLabel.h"
#import "Masonry.h"
#import "UIColor+XYColor.h"
@implementation DanmakuConfigure

@end

@interface DanmakuLabel()<CAAnimationDelegate>
{
    unsigned int _completeCount;
}

@property (nonatomic, strong) DanmakuConfigure *configure;

@property (nonatomic, assign) unsigned int repeatCount;

@end

@implementation DanmakuLabel

@synthesize delegate;

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
-(void)drawTextInRect:(CGRect)rect {

    CGSize shadowOffset = self.shadowOffset;
    UIColor *textColor = self.textColor;

    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(c, 1);
    CGContextSetLineJoin(c, kCGLineJoinRound);

    self.shadowOffset = CGSizeMake(0, 0);
    CGContextSetTextDrawingMode(c, kCGTextStroke);
    self.textColor = self.shadowColor;
    [super drawTextInRect:rect];

    CGContextSetTextDrawingMode(c, kCGTextFill);
    self.textColor = textColor;
//    self.shadowOffset = CGSizeMake(0, 0);
    [super drawTextInRect:rect];

    self.shadowOffset = shadowOffset;

}

+(instancetype)createDanmakuLabelWithConfig:(DanmakuConfigure*)configure inView:(UIView*)view delegate:(id<DanmakuDelegate>)delegate
{
    if (view == nil)
    {
        view = [UIApplication sharedApplication].keyWindow;
    }
    
    DanmakuLabel *ret = [[DanmakuLabel alloc] init];
    ret.backgroundColor = [UIColor clearColor];
    CGFloat font = 0;
    if (configure.captionModel.fontType == NemoCaptionFontSizeSmall) {
        font = 17;
    }else if (configure.captionModel.fontType == NemoCaptionFontSizeMiddle) {
        font = 21;
    }else {
        font = 25;
    }
    ret.font = [UIFont systemFontOfSize:font];
    ret.textColor = [UIColor colorWithHexString:configure.captionModel.fontColor];
    if (configure.captionModel.bgColorAlpha==0) {
        ret.shadowColor = [UIColor colorWithWhite:0 alpha:0.8];
    }else{
        ret.shadowColor = [UIColor clearColor];
    }
    ret.textAlignment = NSTextAlignmentCenter;
    ret.text = configure.captionModel.content;
    ret.numberOfLines = 0;
    ret.lineBreakMode = NSLineBreakByWordWrapping;
    
    ret.configure = configure;
    ret.repeatCount = (!configure.captionModel.scroll? 1 : 0);
    
    CGSize size = [configure.captionModel.content sizeWithAttributes:@{NSFontAttributeName:ret.font}];
    CGFloat height = 44;
    if (configure.captionModel.fontType == NemoCaptionFontSizeSmall) {
        height = 36;
    }else if (configure.captionModel.fontType == NemoCaptionFontSizeBig){
        height = 48;
    }

    [view addSubview:ret];
    size.height = height;
    if (!configure.captionModel.scroll) {
        //固定
        [ret updateDanmakuLayoutInView:view size:size];
    }else{
        if (ret.configure.location == Danmaku_upper){
            if (view.bounds.size.width > view.bounds.size.height) {
                ret.frame = CGRectMake(view.bounds.size.width,0, size.width,height);
            }else{
                ret.frame = CGRectMake(view.bounds.size.width, [DanmakuLabel isFullScreen] ? 34:0, size.width,height);
            }
        } else if (ret.configure.location == Danmaku_middle){
            ret.frame = CGRectMake(view.bounds.size.width, (view.bounds.size.height-height)/2, size.width,height);
        } else{
            ret.frame = CGRectMake(view.bounds.size.width, view.bounds.size.height-height, size.width, height);
        }
    }
    ret.delegate = delegate;
    return ret;
}

+ (BOOL)isFullScreen {
#if __clang_major__ > 10
    if (@available(iOS 11.0, *)) {
#else
    if ([UIDevice currentDevice].systemVersion.floatValue >= 11) {
#endif
        CGFloat height = [[UIApplication sharedApplication] delegate].window.safeAreaInsets.bottom;
        return (height > 0);
    } else {
        return NO;
    }
}

-(id)init
{
    self = [super init];
    if (self)
    {
        _isRunning = NO;
        _completeCount = 0;
        _repeatCount = 0;
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pause) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resume) name:UIApplicationDidBecomeActiveNotification object:nil];
    return self;
}

-(void)start
{
    [self resume];
}

-(void)stop
{
    [self.layer removeAllAnimations];
    [self removeFromSuperview];
}

-(void)pause
{
    if (!_configure.captionModel.scroll)
    {
        return;
    }
    
    if (!_isRunning)
    {
        return;
    }
    
    _isRunning = NO;
    
    self.frame = self.layer.presentationLayer.frame;
    [self.layer removeAllAnimations];
}

-(void)resume
{
    if (_isRunning)
    {
        return;
    }
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position.x"];
    if (!_configure.captionModel.scroll)
    {
        animation.fromValue = [NSNumber numberWithFloat:self.superview.frame.size.width/2];
        animation.toValue = [NSNumber numberWithFloat:self.superview.frame.size.width/2];
        animation.duration = CGFLOAT_MAX;
    }
    else
    {
        NSInteger speed = 0;
        if ([_configure.captionModel.scrollSpeed isEqualToString:@"slow"]) {
            speed = 5;
        }else if ([_configure.captionModel.scrollSpeed isEqualToString:@"middle"]) {
            speed = 10;
        }else {
            speed = 15;
        }
        
        CGFloat durationTime = speed * (self.frame.origin.x + self.frame.size.width) / self.superview.bounds.size.width;
        
        animation.fromValue = [NSNumber numberWithFloat:self.center.x];
        animation.toValue = [NSNumber numberWithFloat:-self.frame.size.width/2];
        animation.duration = durationTime;
    }
    
    
    animation.delegate = self;
    
    [self.layer addAnimation:animation forKey:@"danmaku"];
    
    _isRunning = YES;
}
-(void)updateDanmakuLayoutInView:(UIView*)view size:(CGSize)size{
    if (self.configure.location == Danmaku_upper)
    {
        if (view.bounds.size.width > view.bounds.size.height) {
            self.frame = CGRectMake((view.bounds.size.width - size.width) * 0.5 ,0, size.width, size.height);
        }else{
            self.frame = CGRectMake((view.bounds.size.width - size.width) * 0.5 , [DanmakuLabel isFullScreen] ? 34:0, size.width, size.height);
        }
    } else if (self.configure.location == Danmaku_middle){
        self.frame = CGRectMake((view.bounds.size.width - size.width) * 0.5, (view.bounds.size.height-size.height)/2, size.width, size.height);
    }else{
        self.frame = CGRectMake((view.bounds.size.width - size.width) * 0.5, view.bounds.size.height-size.height, size.width, size.height);
    }
}
-(void)animationDidStart:(CAAnimation *)anim
{
    [self statusBarOrientationChange];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    if (!flag)
        return;
    
    ++_completeCount;
    
    if (_repeatCount != 0 && _completeCount >= _repeatCount)
    {
        [self stop];
        
        if (delegate && [delegate respondsToSelector:@selector(danamkuDidFinished:)])
        {
            [delegate danamkuDidFinished:self];
        }
    }
    else
    {
        //next round
        _isRunning = NO;
        [self resume];
    }
}
-(void)statusBarOrientationChange{
    CGRect frame = self.frame;
    if (frame.origin.x != self.superview.bounds.size.width){
        frame.origin.x = self.superview.bounds.size.width;
        self.frame = frame;
    }
}

@end
